package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.entity.UserInfo;
import io.netty.util.internal.StringUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final String SESSION_KEY = "dfafjal";

//    /**
//     * 注册(忽略)
//     * @param username
//     * @param password
//     * @return
//     */
//    @RequestMapping("reg")
//    public AjaxResult reg(HttpServletRequest request, String username, String password) {
//        //非空校验
//        if(!StringUtils.hasLength(username) && !StringUtils.hasLength(password)) {
//            return AjaxResult.error("参数错误");
//        }
//        UserInfo userInfo = new UserInfo();
//        userInfo.setUsername(username);
//        userInfo.setPassword(password);
//        //创建会话信息，持久化到 Redis 上
//        HttpSession session = request.getSession(true);
//        session.setAttribute(SESSION_KEY, userInfo);
//        //返回成功的结果
//        return AjaxResult.success(1);
//    }

    /**
     * 用户登录
     * @param request
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public AjaxResult login(HttpServletRequest request, String username, String password) {
        //非空校验
        if(!StringUtils.hasLength(username) && !StringUtils.hasLength(password)) {
            return AjaxResult.error("参数非法");
        }
        //校验密码
        if(!username.equals("zhangsan") || !password.equals("123")) {
            //密码错误
            return AjaxResult.error("账号或密码错误");
        }
        //创建用户
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        //登录成功创建会话信息持久化到Redis
        HttpSession session = request.getSession(true);
        session.setAttribute(SESSION_KEY, userInfo);
        return AjaxResult.success(1);
    }

    /**
     * 用户信息查询(通过 Redis )
     * @param session
     * @return
     */
    @RequestMapping("/show")
    public AjaxResult getUserinfo(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(SESSION_KEY);
        //非空校验
        if(!StringUtils.hasLength(userInfo.getUsername()) &&
                !StringUtils.hasLength(userInfo.getPassword())) {
            //校验为空
            return AjaxResult.error("参数错误");
        }
        return AjaxResult.success(userInfo.getUsername());
    }


}
